from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


# 用户输入模型
class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: Optional[str] = None


# 用户输出模型
class UserOut(BaseModel):
    username: str
    email: EmailStr
    full_name: Optional[str] = None


# 用户入库模型
class UserInDB(BaseModel):
    username: str
    hashed_password: str
    email: EmailStr
    full_name: Optional[str] = None


# 密码加密
def fake_password_hasher(raw_password: str):
    # 秘钥+密码
    return "supersecret" + raw_password


# 用户保存
def fake_save_user(user_in: UserIn):
    # 获取加密后的密码
    hashed_password = fake_password_hasher(user_in.password)
    # 保存用户信息
    user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
    print("User saved! ..not really")
    return user_in_db


@app.post("/user/", response_model=UserOut)
async def create_user(user_in: UserIn):
    user_saved = fake_save_user(user_in)
    return user_saved
